package RpcServer.impl;

import Decoder.CommonDecoder;
import Encoder.CommonEncoder;
import RpcServer.RpcServer;
import Serializer.impl.JsonSerializer;
import Serializer.impl.KryoSerializer;
import handler.NettyServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class RpcServerNetty implements RpcServer {
    @Override
    public void start(int port){
        //定义主线程组，用于接收客户端请求，但是并不做任何逻辑处理
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        //从线程组，主线程组会把相应的请求转交给该线程组，由从线程组去做任务
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try{
            //创建netty服务器
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            //服务器设置绑定两个线程组，并设置相应的助手类【handler】
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 256)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            //返回结果之前，需要对写回客户端的数据进行编码处理
                            pipeline.addLast(new CommonEncoder(new KryoSerializer()));
                            //当请求到服务端，我们需要对写出到客户端的数据做解码处理
                            pipeline.addLast(new CommonDecoder());
                            //自定义的，用来处理请求的handler
                            pipeline.addLast(new NettyServerHandler());
                        }
                    });
            System.out.println("server 正在监听...");
            ChannelFuture future = serverBootstrap.bind(port).sync();
            future.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
//            System.out.println("？？");
        }
    }
}
